<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="设备名称或Ip" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.areaId" placeholder="区域" clearable class="filter-item" style="width: 130px">
        <el-option label="全部" value="" />
        <el-option v-for="item in areaList" :key="item.Id" :label="item.Name" :value="item.Id" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="synchronization">
        立即同步
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="$router.go(-1)">
        返回
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column label="设备编号" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.Code }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Mac" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.Mac }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Ip" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.Ip }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Addr" align="center">
        <template slot-scope="{row}">
          <span>{{ row.Manufactor }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageCode" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="模板名称" prop="Name">
          <el-input v-model="temp.Name" />
        </el-form-item>

        <el-form-item label="模板描述" prop="Description">
          <el-input v-model="temp.Description" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import * as homeHttp from '@/api/home'


export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '在线': 'success',
        '离线': 'info',
        // deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageCode: 1,
        pageSize: 10,
        status: undefined,
        name: undefined,
        areaId: undefined,
      },
      importanceOptions: [1, 2, 3],
      areaList: [],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        AreaId: undefined,
        Code: undefined,
        Manufactor: undefined,
        Mac: undefined,
        Ip: undefined,
        Addr: undefined,
        id: undefined,
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改设备',
        create: '添加设备'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      Ids: []
    }
  },
  created() {
    this.configId = this.$route.query.Id
    this.getList()
    this.getAllArea()
  },
  methods: {
    async getList() {
      this.listLoading = true

      const res = await homeHttp.getDevice({
        ...this.listQuery,
        pageCode: this.listQuery.pageCode - 1
      })

      if (res.Result) {
        this.list = res.Data
        this.total = res.Total
      }
      this.listLoading = false
    },
    handleFilter() {
      this.listQuery.pageCode = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },

    resetTemp() {
      this.temp = {
        AreaId: undefined,
        Code: undefined,
        Manufactor: undefined,
        Mac: undefined,
        Ip: undefined,
        Addr: undefined,
        id: undefined,
      }
    },
    async synchronization() {
      const res = await homeHttp.UpdateDeviceConfigPrototype({
        ConfigTemplatePrototypeId: this.configId,
        DeviceIds: this.Ids
      })
      if (res.Result){
        this.$notify({
          title: '成功',
          message: res.Msg || '同步成功',
          type: 'success',
          duration: 2000
        })
        this.$router.go(-1)
      }
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          homeHttp.AddDevice(this.temp).then((res) => {
            if (res.Result) {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: res.Msg || '新增成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          homeHttp.EditDevice(tempData).then(res => {
            if (res.Result) {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: res.Msg || '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            }
          })
        }
      })
    },
    async handleDelete(row, index) {
      const res = await homeHttp.DelDevice({ Id: row.Id })

      if (res.Result) {
        this.getList()
        this.$notify({
          title: '成功',
          message: res.Msg || '删除成功',
          type: 'success',
          duration: 2000
        })
      }
    },

    handleConfig(row) {
      this.$router.push({ path: '/Home/equipmentConfig', query: { Id: row.Id } })
    },

    async getAllArea() {
      const res = await homeHttp.getAllArea()

      if (res.Result) {
        this.areaList = res.Data
      }
    },

    handleSelectionChange(val) {
      val.filter(e=>{
        this.Ids.push(e.Id)
      })
    }
  }
}
</script>
